package com.myCommunity.dao.impl;

import java.sql.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.myCinema.dao.HibernateUtil;
import com.myCommunity.dao.TopicDao;
import com.myCommunity.entity.Topic;
import com.myCommunity.entity.Users;

public class TopicDaoImpl implements TopicDao {

	public List<Topic> getTopicList(int pageNum, int pageSize) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			String hql = "FROM Topic ORDER BY updateTime DESC";
			return sess.createQuery(hql).setFirstResult((pageNum-1)*pageSize)
					.setMaxResults(pageSize).list();
		}finally{
			sess.close();
		}
	}
	
	public static void main(String[] args) {
		Session sess = HibernateUtil.openSession();
		Users user = (Users) sess.get(Users.class, 4);
		Topic t = new Topic(0, "test1", "...", Date.valueOf("2017-02-14"), 3, "201.32.12", 0, Date.valueOf("2017-02-14"), 0, 0, 1);
		t.setUser(user);
		new TopicDaoImpl().add(t);
		
	}

	public List<Topic> getTopicListByForumId(int pageNum, int pageSize,
			int forumId,int isBest) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			String hql = "from Topic where forumId = :forumId and isBest = :isBest";
			Query q = sess.createQuery(hql);
			q.setInteger("forumId", forumId);
			q.setInteger("isBest", isBest);
			return q.setFirstResult((pageNum-1)*pageSize)
					.setMaxResults(pageSize).list();
		}finally{
			if(sess != null)
				sess.close();
		}
	}

	public int getTopicSize(int isBest,int forumId) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Query q = sess.createQuery("from Topic where isBest = :isBest and forumId = :forumId");
			q.setInteger("isBest", isBest);
			q.setInteger("forumId", forumId);
			return q.list().size();
		}finally{
			sess.close();
		}
	}

	public List<Topic> getTopicListByTitle(int pageNum, int pageSize,
			String title) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Query q = sess.createQuery("from Topic where title like :title");
			q.setString("title", "%"+title+"%");
			if(pageNum > 0 && pageSize > 0 )
				return q.setFirstResult((pageNum-1)*pageSize).setMaxResults(pageSize).list();
			
			return q.list();
		}finally{
			sess.close();
		}
	}

	public Topic getTopicById(int id) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Criteria cri = sess.createCriteria(Topic.class);
			cri.add(Restrictions.eq("id", id));
			return (Topic) cri.uniqueResult();
		}finally{
			sess.close();
		}
	}

	public void add(Topic topic) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Transaction tx = sess.beginTransaction();
			sess.save(topic);
			tx.commit();
		}finally{
			sess.close();
		}
	}
	
	

}
